<?php


namespace app\service;


use app\core\exception\BusinessException;
use app\core\Service;
use app\model\TempleImage;
use think\facade\Db;

class TempleImageService extends Service
{

    public function list($page, $limit, $searchQuery = null)
    {
        $w = [];
        if (!empty($searchQuery['temple_id']) && $searchQuery['temple_id'] != '') {
            $w[] = ['temple_id', '=', $searchQuery['temple_id']];
        }
        $map = TempleImage::where($w)->page($page, $limit);
        return [
            'total' => $map->count(),
            'list' => $map->select(),
        ];
    }

    public function save($data)
    {
        Db::startTrans();
        try {
            if (!empty($data['id'])) {
                $info = TempleImage::where('id', $data['id'])->find();
                if (!$info) {
                    throw new BusinessException('数据不存在');
                }
                $info->save([
                    'temple_id' => $data['temple_id'],
                    'img_url' => $data['img_url']
                ]);
            } else {
                TempleImage::create([
                    'temple_id' => $data['temple_id'],
                    'img_url' => $data['img_url']
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw new BusinessException($e->getMessage());
        }
        return true;
    }

    public function del($id)
    {
        $info = TempleImage::where('id', $id)->find();
        if (!$info) {
            throw new BusinessException('数据不存在');
        }
        return $info->delete();
    }
}